const WebSocket = require('ws');

class WebSocketServer {
  constructor() {
    this.server = null;
    this.tcpServer = null;
    this.clients = new Map();
    this.devices  = {};
  }
  setTcpServer(tcpServer) {
    this.tcpServer = tcpServer;
  }
  start(port) {
    this.server = new WebSocket.Server({ port });

    this.server.on('connection', (socket, request) => {
      console.log(request.url.split('/').pop())
      const deviceId = request.url.split('/').pop();
      if (!deviceId) {
        console.error('无效的设备ID');
        socket.close();
        return;
      }

      this.devices[deviceId] = socket;
      this.clients.set(deviceId, socket);
      console.log(`设备ID为${deviceId}的客户端已连接`);

      socket.on('message', (message) => {
        console.log(`收到来自设备ID为${deviceId}的消息： ${message}`);
        if (!this.checkJson(message)) {
          console.log('消息不是有效的JSON格式')
          return
        }
        const res = JSON.parse(message);
        this.tcpServer.sendMessage(res.deviceId, res.message);
      });

      socket.on('close', () => {
        this.clients.delete(deviceId);
        console.log(`设备ID为${deviceId}的客户端已断开连接`);
      });
    });

    console.log(`WebSocket服务器正在监听端口${port}`);
  }

  stop() {
    if (this.server) {
      this.server.close(() => {
        console.log('WebSocket服务器已关闭');
      });
    }
  }

  checkJson(json) {
    try {
      JSON.parse(json);
      return true;
    } catch (error) {
      return false;
    }
  }

  sendMessageToDevice(deviceId, content) {
    if (this.devices[deviceId]) {
      console.log(`发送消息给设备 ${deviceId}：${content}`)
      this.devices[deviceId].send(content);
    } else {
      console.log(`设备 ${deviceId} 未连接`);
    }
  }
}

module.exports = WebSocketServer;

/*// 使用示例
const wsServer = new WebSocketServer();
wsServer.start(3000);

// 发送消息给指定设备ID
wsServer.sendMessageToDevice('123456', 'Hello, Device!');

// 停止WebSocket服务器
wsServer.stop();*/
